package com.kiwi.action;

import com.kiwi.constant.Constant;
import com.kiwi.constant.ConstantURL;
import com.kiwi.util.EncryptSet.Impl.SignatureServiceImpl;
import com.kiwi.util.RedisUtil;
import com.netease.shockwave.http.HttpHandler;
import com.netease.shockwave.http.HttpUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**验证码获取接口
 * Created by bjxiahuifang on 2017/10/9.
 */
@Service
public class SmsCodeAction {
    private static Logger logger = Logger.getLogger(SmsCodeAction.class);
    @Autowired
    private RedisUtil redisUtil;
    public String SmsCodeSend(String mobile,int type,String id,String deviceId) throws Exception {
        String param = String.format("mobile=%s&type=%d", mobile,type);
        SignatureServiceImpl signatureService = new SignatureServiceImpl();
        String params = signatureService.encodeStr(param);
        HashMap<String, String> params_req = new HashMap<String, String>();
        params_req.put("id", id);
        params_req.put("deviceId", deviceId);
        params_req.put("params", params);
        HttpHandler handler = HttpHandler.getInstance();
        String enResult = handler.usingPostMethod(ConstantURL.MOBILESMSCODEURL, params_req, null);
        logger.info(enResult);
        JSONObject jsonRes = HttpUtil.parseJSONObject(enResult);
        //如果验证码发送成功，返回验证码
        if(jsonRes.getString("result").equals("100")) {
            String smsCode = redisUtil.get(Constant.UC_ACCOUNT_SMS_CODE + mobile);
            logger.info("手机号：" + mobile + " 验证码：" + smsCode);
            return smsCode;
        }else{//验证码发送失败，直接返回错误返回码
            logger.info("验证码发送失败返回码："+jsonRes.getString("result"));
            return jsonRes.getString("result");
        }
    }
}
